#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QVariant>
#include <QMessageBox>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(tr("显示网络图片"));
    m_pButton = ui->pushButton;
    m_pButton->setText(QStringLiteral("开始下载"));
    m_pLabel = ui->label;
    m_pLabel->setFixedSize(140, 140);
    m_pLabel->setScaledContents(true);
    connect(m_pButton, SIGNAL(clicked(bool)), this, SLOT(startDownload()));
}

// 点击按钮，开始请求
void MainWindow::startDownload()
{
    m_pButton->setEnabled(false);

    QNetworkRequest request;
    request.setUrl(QUrl("http://avatar.csdn.net/6/9/A/1_u011012932.jpg"));
    connect(&m_networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));
    m_networkManager.get(request);
}

// 响应结束，进行结果处理-图片显示或错误处理
void MainWindow::replyFinished(QNetworkReply *reply)
{
    m_pButton->setEnabled(true);

    //获取响应状态码，200表示正常
    QVariant nCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(200 != nCode) {
        qDebug() << "11111111111" << nCode << "11111111111" << endl;
       // QMessageBox::information(NULL, "提示", "未响应!",QMessageBox::Ok, QMessageBox::Ok);
    }
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        QPixmap pixmap;
        pixmap.loadFromData(bytes);
        m_pLabel->setPixmap(pixmap);

        // 缓存到本地
        QFile file("E:/head.jpg");
        if (file.open(QIODevice::Append))
            file.write(bytes);

        file.close();
    }
    else
    {
        // 错误处理-显示错误信息，或显示上一次缓存的图片或叉图。
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
